const COS = require('./cos-wx-sdk-v5.js'); //  COS 签名方法 
const Bucket = 'p-1301301505';
const Region = 'ap-chongqing';
var prefix = 'https://' + Bucket + '.cos.' + Region + '.myqcloud.com/';
var cdnprefix = "https://"+Bucket+".file.myqcloud.com/";
// const app = getApp();


// 对更多字符编码的 url encode 格式
var camSafeUrlEncode = function (str) {
  return encodeURIComponent(str)
    .replace(/!/g, '%21')
    .replace(/'/g, '%27')
    .replace(/\(/g, '%28')
    .replace(/\)/g, '%29')
    .replace(/\*/g, '%2A');
};
var COSList = [];

var getCOS = function(bucket){
  if (COSList[bucket]) return COSList[bucket];
  var cos = new COS({
      ForcePathStyle: true, // 如果使用了很多存储桶，可以通过打开后缀式，减少配置白名单域名数量，请求时会用地域域名
      getAuthorization: function (options, callback) {
        // if (app.globalData.cosAuth && Date.now() + 2000 < app.globalData.globalData.cosAuth.expiredTime) {
        //   callback(app.globalData.cosAuth.credentials);
        // } else {
          wx.cloud.callFunction({
            name: 'getCOSCredential',
            data: {bucket: bucket},
            success: res => {
              console.log(res);
              // app.globalData.cosAuth = res;
              callback({
                TmpSecretId: res.result.credentials.tmpSecretId,
                TmpSecretKey: res.result.credentials.tmpSecretKey,
                XCosSecurityToken: res.result.credentials.sessionToken,
                ExpiredTime: res.result.expiredTime,
              })
            }
          })
        }
      // }
  });
  COSList[bucket] = cos;
  prefix = 'https://' + Bucket + '.cos.' + Region + '.myqcloud.com/';
  cdnprefix = "https://"+Bucket+".file.myqcloud.com/";
  return cos;
}


var deleteFile = function (options) {
  var key;
  var cos = getCOS(options.bucket);
  if (options.url.indexOf(cdnprefix) == 0){
    key = options.url.substr(cdnprefix.length);
    return;
  } else if (options.url.indexOf(prefix) == 0){
    key = options.url.substr(prefix.length);
  } else{
    wx.cloud.deleteFile({ fileList:[options.url], success: res=>{
      console.log(res);
    }});
    return;
  }
  
  console.log('remove file: ', options.url, key);
  cos.deleteObject({
    Bucket: Bucket,
    Region: Region,
    Key: key
  }, function (err, data) {
    console.log(err || data);
    if (err && options.fail) {
      options.fail(err);
    } else if (options.success) {
      options.success(data);
    }
  });
};


var deleteFiles = function (options) {
  if (!options.files || options.files.length == 0) return;
  var key;
  var cos = getCOS(options.bucket||Bucket);
  var cosFiles = [], cloudFiles = [];
  options.files.map(f=>{
    if (f.indexOf(cdnprefix) === 0){
      cosFiles.push({Key:f.substr(cdnprefix.length)});
    }else if (f.indexOf(prefix) === 0){
      cosFiles.push({Key:f.substr(prefix.length)});
    }else{
      cloudFiles.push(f);
    }
  });
  
  var promise1 = new Promise((resolve, reject)=>{
    if (cloudFiles.length == 0) {
      resolve(false);
      return;
    }
    wx.cloud.deleteFile({ 
      fileList: cloudFiles,
      success: res=>{
        resolve(res);
      },
      fail: e=>{
        console.error(e);
        reject(e)
      }});
  });
  var promise2 = new Promise((resolve, reject)=>{
    cos.deleteMultipleObject({
      Bucket: Bucket,
      Region: Region,
      Objects: cosFiles
    }, function (err, data) {
      if (err){
        console.error(err);
        reject(err);
      }else{
        resolve(data);
      }
    })
  });
  Promise.all([promise1, promise2]).then(res=>{
    console.log(res);
    options.success(res);
  }).catch(e=>{
    options.fail(e);
  });
};

// 上传文件
var uploadFile = function (options) {
  var cos = getCOS(options.bucket);
  cos.postObject({
    Bucket: Bucket,
    Region: Region,
    Key: options.cloudPath,
    FilePath: options.filePath,
    onProgress: function (info) {
      if (options.progress){
        options.progress(info);
      }
      console.log(info);
    }
  }, function (err, data) {
    console.log(err || data);
    if (err){
      if (options.fail){
        options.fail(err);
      }
    }else{
      var url = cdnprefix + camSafeUrlEncode(options.cloudPath).replace(/%2F/g, '/');
      options.success({ fileID: url});  
    }
  });
}


module.exports = {
  uploadFile,
  deleteFile,
  deleteFiles
}